<template>
  <div class="frame-container">
    <!-- 添加搜索区域 -->
    <div class="search-container">
      <div class="search-box">
        <i class="search-icon">🔍</i>
        <input 
          type="text" 
          v-model="searchKeyword"
          @input="handleSearch"
          placeholder="搜索车架型号、品牌或描述..."
        >
        <button 
          class="clear-btn" 
          v-if="searchKeyword"
          @click="clearSearch"
        >
          ✕
        </button>
      </div>
    </div>

    <div class="header">
      <div class="title">选择车架类型</div>
      <div class="tab-group">
        <button 
          :class="['tab-btn', { active: tan }]" 
          @click="handle1"
        >
          <i class="icon">🚲</i>
          碳纤维车架
        </button>
        <button 
          :class="['tab-btn', { active: hejin }]" 
          @click="handle2"
        >
          <i class="icon">🚴</i>
          合金车架
        </button>
      </div>
    </div>

    <!-- 添加搜索结果提示 -->
    <div class="search-result-info" v-if="searchKeyword">
      搜索 "{{ searchKeyword }}" 的结果 ({{ filteredFrameList.length }}个)
      <button class="reset-btn" @click="clearSearch">重置搜索</button>
    </div>

    <div class="frame-grid" v-if="tan">
      <div class="card" v-for="item in filteredFrameList" :key="item.id">
        <div class="card-image">
          <img v-lazy="item.photo" :alt="item.name" />
          <div class="hover-info">
            <p>{{ item.describe }}</p>
          </div>
        </div>
        <div class="card-content">
          <h3 class="product-name">{{ item.name }}</h3>
          <p class="product-desc">{{ item.describe }}</p>
          <div class="card-footer">
            <div class="price">¥{{ item.price.toLocaleString() }}</div>
            <button class="add-btn" @click="add(item.id)">
              <span>加入购物车</span>
              <i class="cart-icon">🛒</i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="frame-grid" v-if="hejin">
      <div class="card" v-for="item in filteredFrameList2" :key="item.id">
        <div class="card-image">
          <img v-lazy="item.photo" :alt="item.name" />
          <div class="hover-info">
            <p>{{ item.describe }}</p>
          </div>
        </div>
        <div class="card-content">
          <h3 class="product-name">{{ item.name }}</h3>
          <p class="product-desc">{{ item.describe }}</p>
          <div class="card-footer">
            <div class="price">¥{{ item.price.toLocaleString() }}</div>
            <button class="add-btn" @click="add(item.id)">
              <span>加入购物车</span>
              <i class="cart-icon">🛒</i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 无搜索结果提示 -->
    <div class="no-result" v-if="searchKeyword && !hasSearchResults">
      <div class="no-result-icon">😕</div>
      <div class="no-result-text">
        未找到相关车架
        <button class="reset-btn" @click="clearSearch">重置搜索</button>
      </div>
    </div>

    <div class="loading" v-if="isLoading">
      <div class="spinner"></div>
      <span>加载中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { getAllFrameList, getAllFrame2List, addToCart, getUserInfo } from "@/api/index.js";
import { ElMessage } from "element-plus";

// 碳纤维车架数据
const frameList = ref([])
const page1 = ref(1)
const totalPage1 = ref(0)

// 合金车架数据
const frameList2 = ref([])
const page2 = ref(1)
const totalPage2 = ref(0)

const size = 5
const tan = ref(true)
const hejin = ref(false)

// 添加加载状态
const isLoading = ref(false)

// 添加搜索相关的响应式变量
const searchKeyword = ref('')

// 数据获取方法
const getData = async () => {
  try {
    isLoading.value = true
    const res = await getAllFrameList({ page: page1.value, size })
    frameList.value = [...frameList.value, ...res.data]
    totalPage1.value = res.totalPage
  } catch (error) {
    console.error('碳纤维数据加载失败:', error)
  } finally {
    isLoading.value = false
  }
}

const getData2 = async () => {
  try {
    isLoading.value = true
    const res = await getAllFrame2List({ page: page2.value, size })
    frameList2.value = [...frameList2.value, ...res.data]
    totalPage2.value = res.totalPage
  } catch (error) {
    console.error('合金数据加载失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 页面切换
const handle1 = () => {
  tan.value = true
  hejin.value = false
  window.scrollTo(0, 0) // 切换时回到顶部
}

const handle2 = () => {
  tan.value = false
  hejin.value = true
  window.scrollTo(0, 0)
}

// 滚动加载逻辑
const debounce = (fn, delay) => {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), delay)
  }
}

const checkScroll = () => {
  const { scrollTop, clientHeight, scrollHeight } = document.documentElement
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    getNextPage()
  }
}

const getNextPage = () => {
  if (tan.value) {
    if (page1.value < totalPage1.value) {
      page1.value++
      getData()
    }
  } else if (hejin.value) {
    if (page2.value < totalPage2.value) {
      page2.value++
      getData2()
    }
  }
}

// 防抖处理后的滚动事件
const handleScroll = debounce(checkScroll, 200)

// 生命周期
onMounted(async () => {
  await getData()
  await getData2()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

const add = async (id) => {
  try {
    const userInfo = await getUserInfo(); // 确保用户已登录
    if (!userInfo.data) {
      ElMessage.error('请先登录');
      return;
    }

    const res = await addToCart({
      
      frameId: id,
      frameType: tan.value ? 1 : 2 // 1-碳纤维，2-合金
    });

    if (res.code === 200) {
      ElMessage.success('成功加入购物车');
    } else {
      ElMessage.error(res.msg || '加入购物车失败');
    }
  } catch (error) {
    console.error('添加购物车错误:', error);
    if (error.response?.status === 401) {
      ElMessage.error('请先登录');
    } else {
      ElMessage.error('加入购物车失败');
    }
  }
}

// 防抖函数
const handleSearch = debounce(() => {
  // 这里可以添加实时搜索的逻辑
  console.log('Searching:', searchKeyword.value)
}, 300)

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 过滤后的列表
const filteredFrameList = computed(() => {
  if (!searchKeyword.value) return frameList.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return frameList.value.filter(item => 
    item.name.toLowerCase().includes(keyword) ||
    item.describe.toLowerCase().includes(keyword) ||
    (item.brand && item.brand.toLowerCase().includes(keyword))
  )
})

const filteredFrameList2 = computed(() => {
  if (!searchKeyword.value) return frameList2.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return frameList2.value.filter(item => 
    item.name.toLowerCase().includes(keyword) ||
    item.describe.toLowerCase().includes(keyword) ||
    (item.brand && item.brand.toLowerCase().includes(keyword))
  )
})

// 判断是否有搜索结果
const hasSearchResults = computed(() => {
  return (tan.value && filteredFrameList.value.length > 0) ||
         (hejin.value && filteredFrameList2.value.length > 0)
})
</script>

<style lang="css" scoped>
/* 修改整体容器样式 */
.frame-container {
    margin-top: calc(56px + env(safe-area-inset-top)); /* 为头部组件留出空间 */
    min-height: 100vh;
    padding-bottom: 80px;
    box-sizing: border-box;
    background: #f5f7fa;
}

/* 修改搜索容器样式 */
.search-container {
    position: sticky;
    top: calc(56px + env(safe-area-inset-top)); /* 与头部组件底部对齐 */
    left: 0;
    right: 0;
    z-index: 98; /* 确保低于头部组件 */
    background: white;
    padding: 12px 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

/* 修改header部分样式 */
.header {
    padding: 16px;
}

/* 修改内容区域样式 */
.frame-grid {
    padding: 16px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 20px;
}

.tab-group {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 32px;
}

.tab-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 12px;
  background: #f5f5f5;
  color: #666;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tab-btn.active {
  background: #3b82f6;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.icon {
  font-size: 20px;
}

.frame-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  animation: fadeIn 0.3s ease-out;
  margin-bottom: 24px;
}

.card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.card-image {
  position: relative;
  overflow: hidden;
  aspect-ratio: 4/3;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.card:hover .card-image img {
  transform: scale(1.05);
}

.hover-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px;
  transform: translateY(100%);
  transition: transform 0.3s ease;
}

.card:hover .hover-info {
  transform: translateY(0);
}

.card-content {
  padding: 20px;
}

.product-name {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.product-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 16px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.price {
  font-size: 24px;
  font-weight: 600;
  color: #3b82f6;
}

.add-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  background: #3b82f6;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.add-btn:hover {
  background: #2563eb;
  transform: translateY(-2px);
}

.cart-icon {
  font-size: 16px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #666;
  margin-bottom: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 适配移动端 */
@media (max-width: 768px) {
    .search-container {
        padding: 8px 12px;
    }
    
    .header {
        padding: 12px;
    }
    
    .frame-grid {
        padding: 12px;
    }

    .title {
        font-size: 24px;
    }

    .tab-btn {
        padding: 8px 16px;
        font-size: 14px;
    }
}

.search-box {
  position: relative;
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 12px;
  padding: 0 16px;
  transition: all 0.3s ease;
}

.search-box:focus-within {
  background: white;
  box-shadow: 0 0 0 2px #3b82f6;
}

.search-icon {
  font-size: 18px;
  color: #666;
  margin-right: 8px;
}

.search-box input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 12px 0;
  font-size: 16px;
  color: #333;
  outline: none;
}

.search-box input::placeholder {
  color: #999;
}

.clear-btn {
  border: none;
  background: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  font-size: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.clear-btn:hover {
  background: #eee;
  color: #666;
}

.search-result-info {
  margin: 16px 0;
  padding: 8px 16px;
  background: #f8fafc;
  border-radius: 8px;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reset-btn {
  border: none;
  background: #3b82f6;
  color: white;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: #2563eb;
}

.no-result {
  text-align: center;
  padding: 40px 0;
  color: #666;
  margin-bottom: 40px;
}

.no-result-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-result-text {
  font-size: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}
</style>